<template>
  <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="rules"
      label-width="auto"
      class="demo-loginForm"
      :size="size"
      :hide-required-asterisk="true"
      :show-message="true"
      :inline-message="true">
    <el-form-item label="用户名" prop="userName" :required="true" :inline-message="true">
      <el-input v-model="loginForm.userName"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password" :required="!isFace" :inline-message="!isFace">
      <el-input type="password" v-model="loginForm.password"></el-input>
    </el-form-item>
    <el-form-item label="人脸识别登录">
      <el-switch v-model="loginForm.isFace"
                 inline-prompt
                 active-text="是"
                 inactive-text="否" @change="handleChangeFaceLogin"/>
    </el-form-item>
    <el-form-item class="bottom-form-item">
      <el-button type="primary" @click="onSubmit">登录</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </el-form>

  <mine-verify mode="pop"
               :captchaType="captchaType"
               :imgSize="{width:'400px',height:'200px'}"
               ref="verify"></mine-verify>
</template>

<script>
import MineVerify from "@/components/verifition/mine-verify.vue";
import {useRouter} from 'vue-router'
import {login, faceLogin} from "@/api/login";
import {ref, unref, getCurrentInstance} from 'vue'
import {ElMessage} from "element-plus";
import {useStore} from  'vuex'
export default {
  name: "mine-login-form",
  components: {MineVerify},
  setup() {
    const loginFormRef = ref()
    const size = ref('middle')
    const isFace = ref(false)
    const verify = ref(null)
    const captchaType = ref('')
    const router = useRouter()
    const store = useStore()
    const flag = ref(false)
    const {proxy} = getCurrentInstance()
    const loginForm = ref({
      userName: '',
      password: '',
      isFace: false
      // code: ''
    })

    const validatePass = (rule, value, callback) => {
      if (!isFace.value && value === '') {
        callback("密码不可为空")
      } else {
        callback()
      }
    }
    const rules = ref({
      userName: [
        {
          required: true,
          message: '用户名不可为空',
          trigger: 'blur'
        }, {
          min: 6,
          max: 16,
          message: '用户名长度不可低于6位不可高于16位',
          trigger: 'blur'
        }
      ],
      password: [
        {required: !isFace, message: '密码不可为空', trigger: 'blur', validator: validatePass}
      ]
      // code: [{required: true, message: '验证码不可为空', trigger: 'blur'}]
    })


    const onShow = (type) => {
      captchaType.value = type
      verify.value.show()
    }

    proxy.$bus.on('checkSuccess', data => {
      //如果使用人脸登录
      if (loginForm.value.userName === null || loginForm.value.userName === "") {
        ElMessage({
          message: "用户名不可为空",
          type: 'warning',
        })
        return
      }
      if (isFace.value) {
        let video = document.getElementById('video');
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        ctx.drawImage(video, 0, 0, 315, 150);
        let img = document.getElementById('canvas').toDataURL();
        // 截取base64，见：https://help.aliyun.com/knowledge_detail/53535.html
        // base64的图片
        let img64 = img.split("base64,")[1];
        faceLogin({
          userName: loginForm.value.userName,
          img64: img64
        }).then(res => {
          loginAfter(res)
        })
      } else {
        login(loginForm.value).then(res => {
          loginAfter(res)
        })
      }
    })
    let loginAfter = (res) => {
      if (res.success) {
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        store.commit('SET_TOKEN', res.data.token)
        store.commit('SET_ACCOUNT_INFO', JSON.stringify(res.data.accountVO))
        store.commit('SET_PERMISSION', res.data.buttonPermissions)
        router.push("/index")
      } else {
        ElMessage({
          message: res.msg,
          type: 'warning',
        })
      }

    }


    const onSubmit = async () => {
      const form = unref(loginFormRef)
      console.log(form.validate())
      try {
        let validate = await form.validate()
        if (validate) {
          //开启滑块验证
          await onShow('blockPuzzle')
        }
        // 路由跳转
      } catch (err) {
        console.log(err)
      }

    }
    const handleChangeFaceLogin = (val) => {
      isFace.value = val
      if (val) {
        //开启人脸登录
        proxy.$bus.emit('openFace')
      } else {
        proxy.$bus.emit('closeFace')
      }
    }

    return {
      loginForm,
      rules,
      size,
      verify,
      captchaType,
      loginFormRef,
      flag,
      isFace,
      onSubmit,
      handleChangeFaceLogin
    }
  }
}
</script>

<style scoped>
</style>
